import { onBeforeUnmount, onMounted } from "vue";

/**
 * onMounted和onBeforeUnmount的组合, onMounted返回的函数在onBeforeUnmount钩子中执行
 * @param hook
 */
export function useEffect(hook: () => any | (() => any)) {
  let beforeUnmountedCb: () => void;

  onMounted(() => {
    const ret = hook();
    if (typeof ret === "function") {
      beforeUnmountedCb = ret;
    }
  });

  onBeforeUnmount(() => {
    beforeUnmountedCb?.();
  });
}
